# -*- coding:utf-8 -*-

import subprocess
import re
import time
import tempfile

def scan_ip(the_third_field):
    out_temp = tempfile.TemporaryFile(mode='w+')
    fileno = out_temp.fileno()
    popen = subprocess.Popen(['arp', '-a'], stdout=fileno, stderr=fileno)
    popen.wait()
    cmd = 'nmap -sP 192.168.%s.0/24' % str(the_third_field)
    result = subprocess.call(cmd,stdout=fileno, stderr=fileno)

def scan_mac():
    out_temp = tempfile.TemporaryFile(mode='w+')
    fileno = out_temp.fileno()
    
    popen = subprocess.Popen(['arp', '-a'], stdout=fileno, stderr=fileno)
    popen.wait()
    
    out_temp.seek(0)
    read_out = out_temp.read()
    lines = read_out.strip().split('\n')
    
    result_map = {}
    for line in lines:
        if 'Internet' in line:
            continue
        searchObj = re.search(r'(\d+\.\d+\.\d+\.\d+)\s+(.+-.+-.+-.+-.+-.+?)\s+',line)
        if searchObj:
            # print([searchObj.group(1)],[searchObj.group(2)])
            line_ip_addr = searchObj.group(1)
            line_mac_addr = searchObj.group(2)
            result_map[line_mac_addr] = line_ip_addr
    return result_map

def main():
    start_time = time.time()
    
    target1 = [
    ('测试间主PC','f8-bc-12-a8-07-32'),
    ('测试间辅PC','64-00-6a-38-38-c7'),
    ('测试间笔记本','5c-c5-d4-75-ed-d8'),
    ('UT-笔记本1','08-11-96-77-c7-94'),
    ('mini_samba_PC','00-e5-4e-68-13-91'),
    ('PI-smoke1','b8-27-eb-56-7b-ba'),
    ('PI-smoke2','b8-27-eb-63-0e-00'),
    ]
    
    scan_ip(160)
    scan_ip(161)
    scan_ip(162)
    scan_ip(163)
    pool = scan_mac()
    
    for ele in target1:
        name = ele[0]
        mac_addr = ele[1]
        ip_addr = pool[mac_addr]
        print("%s 的IP地址现在是 %s" % (name,ip_addr))
    
    end_time = time.time()
    tsec = round(float((end_time-start_time)),2)
    thour = round(tsec/3600,2)
    print(f"\n等待 {tsec} 秒,等待 {thour} 小时\n")

# 参考了 https://www.cnblogs.com/misswangxing/p/10718556.html
main()